package com.resource.map
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	
	public class MapCacher extends EventDispatcher
	{
		private static var _instance:MapCacher;
		private var _cacher:Object = {};
		
		public static function getInstance():MapCacher{
			if(!_instance){
				_instance = new MapCacher;
			}
			return _instance;
		}
		
		public function MapCacher(target:IEventDispatcher=null)
		{
			super(target);
		}
		
		public function getMapTile(url:String):BitmapData{
			return _cacher[url];
		}
		
		public function load(url:String):void{
			var loader:MapLoader = new MapLoader;
			loader.url = url;
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadComplete);
			loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onError);
			loader.load(new URLRequest(url));
		}
		
		private function loadComplete(event:Event):void{
			var loader:MapLoader = event.currentTarget.loader as MapLoader;
			loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, loadComplete);
			loader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, onError);
			if(!_cacher[loader.url]){
				_cacher[loader.url] = (loader.content as Bitmap).bitmapData;
			}
			var e:MapEvent = new MapEvent(loader.url);
			e.data = _cacher[loader.url];
			e.loader = loader;
			dispatchEvent(e);
		}
		
		private function onError(event:IOErrorEvent):void{
			var loader:MapLoader = event.currentTarget.loader as MapLoader;
			loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, loadComplete);
			loader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, onError);
			var e:MapError = new MapError(loader.url + "error");
			e.loader = loader;
			dispatchEvent(e);
		}
	}
}